package com.example.demo.controller;

import com.example.demo.config.MinioConfig;
import com.example.demo.util.MinioUtil;
import com.example.demo.util.Result;
import com.example.demo.util.ResultUtil;
import io.minio.messages.Bucket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping(value = "/sys/file")
public class FileController {


    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private MinioConfig prop;


    @GetMapping("/bucketExists")
    public Result bucketExists(String bucketName) {
        return ResultUtil.success(minioUtil.bucketExists(bucketName));
    }

    @GetMapping("/makeBucket")
    public Result makeBucket(String bucketName) {
        minioUtil.makeBucket(bucketName);
        return ResultUtil.success();
    }

    @GetMapping("/removeBucket")
    public Result removeBucket(String bucketName) {
        minioUtil.removeBucket(bucketName);
        return ResultUtil.success();
    }

    @GetMapping("/getAllBuckets")
    public Result<List<Bucket>> getAllBuckets() {
        List<Bucket> allBuckets = minioUtil.getAllBuckets();
        return ResultUtil.success(allBuckets);
    }

    @PostMapping("/upload")
    public Result<String> upload(@RequestParam(value = "file") MultipartFile file) {
        String objectName = minioUtil.upload(file);
        if (null != objectName) {
            return ResultUtil.success(prop.getEndpoint() + "/" + prop.getBucketName() + "/" + objectName);
        }
        return ResultUtil.error(1000, "error");
    }

    @GetMapping("/preview")
    public Result preview(@RequestParam("fileName") String fileName) {
        return ResultUtil.success(minioUtil.preview(fileName));
    }

    @GetMapping("/download")
    public Result download(@RequestParam("fileName") String fileName, HttpServletResponse res) {
        minioUtil.download(fileName,res);
        return ResultUtil.success();
    }

    @PostMapping("/delete")
    public Result remove(String url) {
        String objName = url.substring(url.lastIndexOf(prop.getBucketName()+"/") + prop.getBucketName().length()+1);
        minioUtil.remove(objName);
        return ResultUtil.success();
    }

}

